package com.roadjava.rbac.security;

import cn.hutool.core.collection.CollUtil;
import com.roadjava.rbac.bean.dto.SecurityUserDTO;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.servlet.http.HttpServletRequest;
import java.util.Set;



@Component
public class RbacManager {
    private final AntPathMatcher antPathMatcher = new AntPathMatcher();
    /**
     *
     * @return true:security认为有权限,授权成功  false:没权限
     */
    public boolean hasPermission(HttpServletRequest request){
        boolean hasPermission = false;
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Object principal = authentication.getPrincipal();
        if (principal instanceof SecurityUserDTO) {
            SecurityUserDTO dto = (SecurityUserDTO) principal;
            Set<String> backAuthorizedUris = dto.getBackAuthorizedUris();
            if (CollUtil.isEmpty(backAuthorizedUris)) {
                // 没有任何可用权限
                return false;
            }
            for (String authorizedUri : backAuthorizedUris) {
                if (antPathMatcher.match(authorizedUri,request.getRequestURI())) {
                    // 后端用户已授权的权限集合backAuthorizedUris能够匹配当前请求
                    System.out.println("当前用户已授权的权限：" + authorizedUri);
                    hasPermission = true;
                    break;
                }
            }
            return  hasPermission;
        }
        return false;
    }
}
